package cn.fanyamin.web.struts;

import java.util.List;


import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.LazyValidatorForm;

import cn.fanyamin.business.UserService;
import cn.fanyamin.domain.User;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * index.do Action.
 *
 * @version 1.1
 * @since GW 3.3 08/27/2008
  */
public class LoginAction extends BaseAction {
    
    static final int SECONDS_PER_YEAR = 60 * 60 * 24 *30;
    
    private static Log logger = LogFactory.getLog(LoginAction.class);
    /**
     * DOCUMENT ME!
     *
     * @param mapping DOCUMENT ME!
     * @param form DOCUMENT ME!
     * @param request DOCUMENT ME!
     * @param response DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        
        LazyValidatorForm loginForm = (LazyValidatorForm)form;
        String userName = (String)loginForm.get("username");
        String password = (String)loginForm.get("password");
        String remember = (String)loginForm.get("remember");
        
        if(StringUtils.isBlank(userName)||StringUtils.isBlank(password)){
            User ckUser = getUserFromCookie(request);
            if(StringUtils.isBlank(ckUser.getUserName())
                            ||StringUtils.isBlank(ckUser.getPassword())) {
                return mapping.findForward("failure");
            } else {
                userName = ckUser.getUserName();
                password = ckUser.getPassword();
            }
        }
        UserService userService = getWebApp().getUserService();
        User aUser = new User();
        aUser.setUserName(userName);
        List<User> userList = userService.find(aUser);
        if(userList == null || userList.size() != 1) {
            request.setAttribute("errMsg", "user name is not match");
            return mapping.findForward("failure");
        }
        
        
        User user = userList.get(0);
        
        if (StringUtils.isNotBlank(remember)) {
            logger.debug("Save cookies.");
            saveCookie(response, user.getUserName(), user.getPassword());
            request.setAttribute("remeber", "1");
        } else {
            logger.debug("Clear cookies.");
            clearCookie(response);
            request.setAttribute("remeber", "0");
        }
        logger.debug("find a user: " + user);
        if( DigestUtils.md5Hex(password).equals(user.getPassword())) {
            HttpSession session = request.getSession();
            session.setAttribute("sess_user", user);
            return mapping.findForward("success");    
        }
        return mapping.findForward("failure");
    }
    
    
    
    private void saveCookie(HttpServletResponse response, String userName, String md5Password) {
        Cookie usernameCookie = new Cookie(COOKIE_USERNAME, userName);
        usernameCookie.setMaxAge(60*60*24*30);
        response.addCookie(usernameCookie);

        Cookie userpwdCookie = new Cookie(COOKIE_PASSWORD, md5Password);
        userpwdCookie.setMaxAge(SECONDS_PER_YEAR);
        response.addCookie(userpwdCookie);

    }
    
    public static void clearCookie(HttpServletResponse response) {
        Cookie usernameCookie = new Cookie(COOKIE_USERNAME, "");
        usernameCookie.setMaxAge(0);
        response.addCookie(usernameCookie);

        Cookie userpwdCookie = new Cookie(COOKIE_PASSWORD, "");
        userpwdCookie.setMaxAge(0);
        response.addCookie(userpwdCookie);
    }
}
